package com.mindtree.vi.business.javaservice;

import java.io.InputStream;
import java.io.StringWriter;

public class SimpleJavaInterpretationService implements JavaService {

	public ServiceResponse invokeService(ServiceCommandType serviceType,
			String className) {
		ServiceResponse xmlResponse = new ServiceResponse();
		InputStream stream = null;
		Process process;
		try {
			process = Runtime.getRuntime().exec(
					serviceType.getType() + className);
			if (process.getErrorStream().markSupported()) {
				process.getErrorStream().mark(0);
			}
			int firstChar = process.getErrorStream().read();
			boolean error = firstChar != -1;
			if (!error) {
				stream = process.getErrorStream();
			} else {
				stream = process.getErrorStream();
				if (process.getErrorStream().markSupported()) {
					process.getErrorStream().reset();
				}
			}
			StringWriter writer = new StringWriter();
			int data = 0;
			int count = 0;
			while ((data = stream.read()) != -1) {
				count++;
				if (count == 1) {
					writer.write(firstChar);
				}
				writer.write(data);
			}
			System.out.println("count is " + count);
			if (count == 0) {
				xmlResponse.setCode(StatusCode.COMPILE_SUCCESS);
				xmlResponse.setMessage(StatusCode.COMPILE_SUCCESS.name());
			} else {
				xmlResponse.setMessage(writer.getBuffer().toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return xmlResponse;
	}

}
